<template>
  <!-- <view class="flex benben-flex-layout flex-wrap align-center jdt">
		<benben-progress-slider class='lx_fd4_0_ibhf ' v-model="jd" direction="horizontal" :show-buttons='true'
			:step="20" :min="0" :max="100" :track-height="16">

			<template #thumb>
				<view class='flex flex-wrap align-center'>
					<image class='lx_fd4_0_c0_c0_ibhf' mode="aspectFit" :src='STATIC_URL+"stcimg/3.png"'>
					</image>
				</view>
			</template><template #minus>
				<view class='flex flex-wrap align-center'>
					<text class='fu-iconfont2  lx_fd4_0_c1_c0_ibhf'>&#xe680;</text>
				</view>
			</template><template #plus>
				<view class='flex flex-wrap align-center'>
					<text class='fu-iconfont2  lx_fd4_0_c1_c0_ibhf'>&#xe736;</text>
				</view>
			</template>
		</benben-progress-slider>

	</view> -->
  <!-- <view class="tupu-content" :style="{ height: `calc(100vh - 88rpx - 88rpx - 300rpx - ${StatusBarRpx}rpx - var(--window-bottom))` }"> -->
  <!-- 使用renderjs -->
  <view :prop="option" :change:prop="echarts.update" v-if="group==1" class="echarts2" id="echarts2" @tap.stop="jump"></view>
   <view :prop="option" :change:prop="echarts.update" v-else class="echarts2" id="echarts2"></view>
  <!-- </view> -->
  <!--  <view v-show="rawData.length == 0 && false">
    <slot>
      <view class="public-page-empty">
        <image src="/static/global/order.png"></image>
        <view class="txt">暂无数据</view>
      </view>
    </slot>
  </view> -->
</template>

<script>
export default {
  props: {
    course: String,
    jd: Number,
    name: String,
  },
  data() {
    return {
      rawData: [],
      group: uni.getStorageSync('USER_GROUP'),
      // jd:80,
      isup: false,
      option: {
        backgroundColor: '#fff',
        // layout 参数指定了节点位置的计算方式：
        // ‌none‌：不采用预设布局，节点位置由数据中的 x、y 属性直接确定。 ‌
        // ‌circular‌：采用环形布局，节点按圆形或环形排列。 ‌
        // ‌force‌：使用力导向布局（Force Layout），通过物理模拟计算节点位置，常用于复杂网络的可视化。 ‌
        series: [
          {
            type: 'graph',
            layout: 'force',
            roam: false, // 允许缩放和平移
            force: {
              repulsion: 250,
              edgeLength: 10,
              // repulsion: 400,
              // edgeLength: 10
            },
            data: [],
          },
        ],
      },
    }
  },
  mounted() {
    this.get_course_chapterApi()
  },
  methods: {
    async get_course_chapterApi() {
      let url = ''
      let obj = {}
      if (uni.getStorageSync('USER_GROUP') == 1) {
        url = global.apiUrls.post6818697f95795
        obj.course_id = this.course
      } else {
        url = global.apiUrls.post6818697f95795
        obj.course_id = this.course
      }
      let res = await this.$api.post(url, obj)

      // console.log('00000000000000000000000', res);
      this.isup = true
      if (res.data.code == 1) {
        let arr = uni.getStorageSync('USER_GROUP') == 1 ? res.data.data.list : res.data.data.list
        this.rawData = arr.map((item) => {
          return {
            name: item.name,
            value: item.aid,
            size: this.getRandomFromArray(this.jd),
            // size: 80
          }
        })
        
        this.$emit('myEvent', { jindu: res.data.data.num.jindu, total_num: res.data.data.num.total_num })
        // 准备option数据
        const fontSize = 11
        // console.log(this.rawData)
        this.option.series[0].data = this.rawData.map((item) => ({
          name: this.wrapText(item.name, item.size, fontSize),
          value: item.value,
          symbolSize: item.size,
          symbol: 'image://static/img02/yuan.png',
          draggable: false,
          label: {
            show: true,
            position: 'inside',
            fontSize, //文字字体大小
            color: '#FFFFFF',
            align: 'center',
            verticalAlign: 'middle',
            lineHeight: fontSize + 2,
          },
        }))
        // console.log(this.option.series[0].data[0],'3333333333333')
        let params = this.option.series[0].data[0]
        // console.log(
        // 	`/pages/kc/chapterDetail/chapterDetail?aid=${params.value}&course=${this.course}&name=${this.name.replace(/\n/g, '')}`
        // 	)
      }
    },

    //节点大小
    getRandomFromArray(jd) {
      const arr = [120, 130, 110, 100, 90, 80]
      // console.log(Math.random())
      const index = Math.floor(Math.random() * arr.length)
      // console.log(typeof(arr[index]))
      // let jd=this.jd
      // console.log(jd)
      // console.log(typeof(jd))
      return jd
    },

    // 自适应换行文本
    wrapText(text, symbolSize, fontSize = 14) {
      const avgCharWidth = fontSize * 0.6
      const maxLineWidth = symbolSize * 0.5 // 留出 padding
      const maxCharsPerLine = Math.max(2, Math.floor(maxLineWidth / avgCharWidth))
      const lines = []
      for (let i = 0; i < text.length; i += maxCharsPerLine) {
        lines.push(text.slice(i, i + maxCharsPerLine))
      }
      return lines.join('\n')
    },
    jump(e) {
      console.log(e)
      let params = {
        value: 3,
        name: '鸦片战争的爆发',
      }
      return
      uni.navigateTo({
        url: `/pages/kc/chapterDetail/chapterDetail?aid=${params.value}&course=${this.course}&name=${this.name.replace(/\n/g, '')}`,
      })
    },
  },
}
</script>

<script module="echarts" lang="renderjs">
	import * as echarts from 'echarts';

	let chart = null;

	export default {
		mounted() {
			const tryInit = () => {
				const el = document.getElementById('echarts2') || document.querySelector('.echarts2');
				if (!el || el.nodeType !== 1 || !el.offsetWidth || !el.offsetHeight) {
					setTimeout(tryInit, 50);
					return;
				}
				this.init();
			};
			setTimeout(tryInit, 0);
		},
		unmounted() {
			if (chart) {
				chart.dispose();
				chart = null;
			}
		},
		methods: {
			init() {
				const el = document.getElementById('echarts2') || document.querySelector('.echarts2');
				if (!el || el.nodeType !== 1) {
					return;
				}
				chart = echarts.init(el);
				const isDark = document.body.getAttribute('data-theme') === 'dark';
				if (isDark) {
					chart.setOption({ backgroundColor: '#1e1e1e' });
				}
				if (this.prop) {
					this.update(this.prop);
				}
				chart.on('click', (params) => {
					uni.navigateTo({
						url: `/pages/kc/chapterDetail/chapterDetail?aid=${params.value}&course=${this.course}&name=${this.name.replace(/\n/g, '')}&nameTitle=${params.name}`
					});
				});
			},
			update(newOption) {
				if (!chart) {
					const el = document.getElementById('echarts2') || document.querySelector('.echarts2');
					if (el && el.nodeType === 1 && el.offsetWidth && el.offsetHeight) {
						chart = echarts.init(el);
					} else {
						return;
					}
				}
				chart.setOption(newOption);
			},
			resize() {
				if (chart) {
					chart.resize();
				}
			}
		}
	};
</script>

<style scoped>
.jdt {
  width: 100%;
  background-color: #f4f8fd;
  height: 100rpx;
}
.lx_fd4_0_ibhf {
  width: 750rpx;
  height: 36rpx;
  padding: 0rpx 30rpx 0rpx 30rpx;
  --track-bg: #ff6600;
  --track-wrapper-bg: #ccc;
}
.lx_fd4_0_c0_c0_ibhf {
  width: 36rpx;
  height: 36rpx;
  border-radius: 0rpx;
}

.lx_fd4_0_c1_c0_ibhf {
  color: var(--benbenFontColor2);
}
.tupu-content {
  min-height: 70%;
  width: 100%;
}

.echarts2 {
  width: 100%;
  min-height: 70%;
}
.public-page-empty {
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
  padding: 120upx 0 0 0;

  image {
    width: 300rpx;
    height: 300rpx;
  }

  .txt {
    font-size: 28upx;
    color: $uni-text-color;
    text-align: center;
    line-height: 100upx;
    color: var(--benben-loading-color, #999999);
  }

  .loadTips {
    line-height: 30upx;
  }

  .btn {
    width: 260upx;
    height: 78upx;
    line-height: 78upx;
    background: linear-gradient(309deg, rgba(254, 49, 0, 1) 0%, rgba(255, 90, 16, 1) 100%);
    opacity: 1;
    border-radius: 44upx;
    font-size: 28upx;
    color: #fff;
    text-align: center;
    margin-top: 100upx;
  }
}
</style>
